<?php
// +----------------------------------------------------------------------
// | SparkERP 优秀的进销存系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://erp.sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai  <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\service\data;

use app\model\data\Brand;
use app\model\data\BrandCateRelation;
use app\validate\data\BrandValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;

class BrandService
{
    private Brand $brandModel;
    private BrandCateRelation $relationModel;

    public function __construct(Brand $brandModel, BrandCateRelation $relationModel)
    {
        $this->brandModel = $brandModel;
        $this->relationModel = $relationModel;
    }

    /**
     * 获取品牌列表
     * @param array $param
     * @return array
     * @throws DbException
     */
    public function getList(array $param): array
    {
        $limit = $param['limit'];
        $name = $param['name'] ?? '';

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $list = $this->brandModel->where($where)->order('sort asc, id desc')->paginate($limit)
            ->each(function ($item) {
                // 获取关联的分类信息
                $categories = $this->relationModel->where('brand_id', $item['id'])
                    ->with('brandCate')
                    ->select()
                    ->toArray();

                $cateNames = [];
                foreach ($categories as $cate) {
                    $cateNames[] = $cate['brandCate']['name'];
                }
                $item['category_ids'] = array_column($categories, 'cate_id');
                $item['category_names'] = implode(',', $cateNames);

                return $item;
            });

        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加品牌
     * @param array $param
     * @return array
     */
    public function addBrand(array $param): array
    {
        // 检验完整性
        try {
            validate(BrandValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        $has = $this->brandModel->checkUnique([
            'name' => $param['name']
        ])['data'];

        if (!empty($has)) {
            return dataReturn(-2, '该品牌名称已经存在');
        }

        // 提取分类ID
        $categoryIds = $param['category_ids'] ?? [];
        unset($param['category_ids']);

        $param['create_time'] = now();
        
        // 开启事务
        $this->brandModel->startTrans();
        try {
            $result = $this->brandModel->insertOne($param);
            if ($result['code'] != 0) {
                $this->brandModel->rollback();
                return $result;
            }
            
            $brandId = $result['data'];
            
            // 保存品牌分类关联
            if (!empty($categoryIds)) {
                $this->saveBrandCategories($brandId, $categoryIds);
            }
            
            $this->brandModel->commit();
            return dataReturn(0, '添加成功', $brandId);
        } catch (\Exception $e) {
            $this->brandModel->rollback();
            return dataReturn(-1, $e->getMessage());
        }
    }

    /**
     * 编辑品牌
     * @param array $param
     * @return array
     */
    public function editBrand(array $param): array
    {
        // 检验完整性
        try {
            validate(BrandValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $this->brandModel->checkUnique($where)['data'];

        if (!empty($has)) {
            return dataReturn(-2, '该品牌名称已经存在');
        }

        // 提取分类ID
        $categoryIds = $param['category_ids'] ?? [];
        unset($param['category_ids']);

        $param['update_time'] = now();
        
        // 开启事务
        $this->brandModel->startTrans();
        try {
            $result = $this->brandModel->updateById($param, $param['id']);
            if ($result['code'] != 0) {
                $this->brandModel->rollback();
                return $result;
            }
            
            // 删除原有关联，重新保存
            $this->relationModel->delByWhere(['brand_id' => $param['id']]);
            
            // 保存新的品牌分类关联
            if (!empty($categoryIds)) {
                $this->saveBrandCategories($param['id'], $categoryIds);
            }
            
            $this->brandModel->commit();
            return dataReturn(0, '更新成功');
        } catch (\Exception $e) {
            $this->brandModel->rollback();
            return dataReturn(-1, $e->getMessage());
        }
    }

    /**
     * 删除品牌
     * @param int $id
     * @return array
     */
    public function delBrand(int $id): array
    {
        // 开启事务
        $this->brandModel->startTrans();
        try {
            // 删除品牌分类关联
            $this->relationModel->delByWhere(['brand_id' => $id]);
            
            // 删除品牌
            $result = $this->brandModel->delById($id);
            
            $this->brandModel->commit();
            return $result;
        } catch (\Exception $e) {
            $this->brandModel->rollback();
            return dataReturn(-1, $e->getMessage());
        }
    }

    /**
     * 保存品牌分类关联
     * @param int $brandId
     * @param array $categoryIds
     * @return void
     */
    private function saveBrandCategories(int $brandId, array $categoryIds): void
    {
        $relations = [];
        foreach ($categoryIds as $cateId) {
            $relations[] = [
                'brand_id' => $brandId,
                'cate_id' => $cateId,
                'create_time' => now(),
                'update_time' => now()
            ];
        }
        
        if (!empty($relations)) {
            $this->relationModel->insertBatch($relations);
        }
    }
}